package com.bnd.service.impl;

import com.bnd.service.FileService;
import com.bnd.utils.AudioFileValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletResponse;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.nio.file.*;
import java.util.UUID;

/**
 * 文件服务实现类
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {
    @Value("${proxy.url}")
    private String BASE_URL;
    private static final String UPLOAD_DIR = System.getProperty("user.dir") + "/ai-roleplay-hub-backend/uploads";

    /**
     * 文件上传
     * @param file 上传的文件
     * @return 文件访问URL
     * @throws IOException IO异常
     */
    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 创建上传目录路径
        Path uploadPath = Paths.get(UPLOAD_DIR);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

        // 保存文件
        Path filePath = uploadPath.resolve(uniqueFilename);
        Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

        log.info("文件上传成功，原始文件名: {}, 存储路径: {}", originalFilename, filePath.toAbsolutePath());

        // 返回可访问的 URL
        return BASE_URL + "/uploads/" + uniqueFilename;
    }

    /**
     * 音频文件上传（带校验）
     * @param file 上传的音频文件
     * @return 文件访问URL
     * @throws IOException IO异常
     */
    @Override
    public String uploadAudioFile(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("音频文件不能为空");
        }

        // 音频文件校验
        AudioFileValidator.validateAudioFile(file);

        // 复用普通文件上传逻辑
        return uploadFile(file);
    }

    /**
     * 文件下载
     * @param fileUrl 文件访问URL
     * @param response HTTP响应对象
     * @throws IOException IO异常
     */
    @Override
    public void downloadFile(String fileUrl, HttpServletResponse response) throws IOException {
        String fileName = extractFilename(fileUrl);
        Path filePath = Paths.get(UPLOAD_DIR).resolve(fileName);

        if (!Files.exists(filePath)) {
            throw new FileNotFoundException("文件不存在: " + fileUrl);
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        try (InputStream inputStream = Files.newInputStream(filePath);
             OutputStream outputStream = response.getOutputStream()) {
            inputStream.transferTo(outputStream); // 简化拷贝
            outputStream.flush();
        }

        log.info("文件下载成功，文件URL: {}", fileUrl);
    }

    /**
     * 文件删除
     * @param fileUrl 文件访问URL
     * @return 是否删除成功
     */
    @Override
    public boolean deleteFile(String fileUrl) {
        try {
            String fileName = extractFilename(fileUrl);
            Path filePath = Paths.get(UPLOAD_DIR).resolve(fileName);

            if (Files.exists(filePath)) {
                Files.delete(filePath);
                log.info("文件删除成功，文件路径: {}", filePath);
                return true;
            } else {
                log.warn("尝试删除不存在的文件，文件路径: {}", filePath);
                return false;
            }
        } catch (IOException e) {
            log.error("文件删除失败，文件URL: {}", fileUrl, e);
            return false;
        }
    }

    /**
     * 文件预览
     * @param fileUrl 文件访问URL
     * @return Resource资源对象
     * @throws MalformedURLException URL异常
     */
    @Override
    public Resource previewFile(String fileUrl) throws MalformedURLException {
        String fileName = extractFilename(fileUrl);
        Path filePath = Paths.get(UPLOAD_DIR).resolve(fileName);

        if (Files.exists(filePath)) {
            return new UrlResource(filePath.toUri());
        }
        return null;
    }

    /**
     * 从 URL 提取文件名
     */
    private String extractFilename(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            throw new IllegalArgumentException("文件URL不能为空");
        }
        return fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
    }
}
